<script setup lang="ts">
import { ref, computed } from 'vue'

import { shuffleArray } from '@/utils'
import { TurntableGameAudio } from '@/utils/videoCtx.ts'

const emit = defineEmits(['end'])

const imgSort = ref([0, 1, 2, 4, 7, 6, 5, 3])
const getTurnTableIcon = (url: string) => {
    return new URL(`/src/assets/imgs/lottery/icon/${url}`, import.meta.url).href
}

const startStep = computed(() => Math.floor(baseCircle * 8 * (1 / 3)))
const midStep = computed(() => Math.floor(totalStep.value * (5 / 8)))
const fastSpeed = 100
const slowSpeed = 800
const initSpeed = 200
const calcSpeed = (speed = 300) => {
    // 匀加速
    if (currentStep.value < startStep.value && speed > fastSpeed) {
        speed = speed - Math.floor((initSpeed - fastSpeed) / startStep.value)
    }

    // 减速
    if (currentStep.value > midStep.value && speed < slowSpeed) {
        speed = speed + Math.floor((slowSpeed + fastSpeed) / startStep.value / 4)
    }

    return speed
}

const timer = ref(0)
const currentAwardIndex = ref(0)
const currentStep = ref(0)
const speed = ref(150)
const removeSort = [0, 1, 2, 4, 7, 6, 5, 3]
const targetId = 5
const baseCircle = 3
const totalStep = computed(() => {
    return baseCircle * 8 + removeSort.indexOf(targetId)
})
const gameAudio = new TurntableGameAudio()
const initTurntable = () => {
    imgSort.value = shuffleArray([0, 1, 2, 4, 7, 6, 5, 3])
    currentAwardIndex.value = 0
    speed.value = 150
    currentStep.value = 0
    timer.value = 0
}
const startLottery = () => {
    timer.value && clearTimeout(timer.value)

    if (currentAwardIndex.value == removeSort.indexOf(targetId) && currentStep.value >= totalStep.value) {
        emit('end')
        // this.totalPoints = this.userInfo.totalPoints
        return
    }

    currentAwardIndex.value = removeSort[currentStep.value % 8]

    speed.value = calcSpeed(speed.value)

    timer.value = window.setTimeout(() => {
        gameAudio.systemAudio()
        currentStep.value++
        startLottery()
    }, speed.value)
}

defineExpose({
    startLottery,
    initTurntable
})
</script>

<template>
    <div class="truntable">
        <ul class="main-lotter">
            <li class="main-lotter-item" :class="{ 'main-lotter-item_active': key === currentAwardIndex }"
                v-for="(item, key) in imgSort">
                <div class="main-lotter-item-icon">
                    <img class="main-lotter-item-icon_img" :src="getTurnTableIcon(`${item}.png`)" :alt="`icon_${item}`"
                        width="60">
                </div>
            </li>
        </ul>
    </div>
</template>

<style scoped lang="scss">
@import url(./index.scss);
</style>